package pool 
{
	/**
	 * 抽象池
	 * @author gcxk721
	 */
	public class AbstrackPool implements IPool 
	{
		
		/**
		 * 当前池中的保持对象
		 */
		protected var m_keeps : int;
		
		/**
		 * 池中对象
		 */
		protected var m_cls : Class;
		
		/**
		 * 池对象的记录容器
		 */
		protected var m_Items : Vector.<IPoolObject> = new Vector.<IPoolObject>();
		
		public function AbstrackPool(keeps : int, cls : Class) 
		{
			m_keeps = keeps
			m_cls = cls;
		}
		
		/* INTERFACE pool.IPool */
		public function getItem(value : * = null):IPoolObject 
		{
			var item : IPoolObject = findIdelItem(value);
			if (item == null)
			{
				item = new m_cls();
				m_Items.push(item);
			}
			item.used();
			return item;
		}
		
		public function releaseItem(item : IPoolObject) : void 
		{
			for (var i : int = 0; i < m_Items.length; ++i)
			{
				if (item == m_Items[i])
				{
					m_Items[i].released();
					return;
				}
			}
		}
		
		/**
		 * 找出当前没有使用的池对象
		 * @return
		 */
		protected function findIdelItem(value : * = null) : IPoolObject
		{
			for (var i : int = 0; i < m_Items.length; ++i)
			{
				if (!m_Items[i].isUsed())
				{
					return m_Items[i];
				}
			}
			return null;
		}
		
		/**
		 * 清理对象池的函数
		 */
		public function cleanPool() : void
		{
			var itemNum : int = m_Items.length;
			if (itemNum > m_keeps)//当前数量大于保持数量
			{
				//清理没有使用的
				var cleanNum : int = itemNum - m_keeps;
				for (var i : int = 0; i < m_Items.length; ++i)
				{
					if (!m_Items[i].isUsed())
					{
						m_Items[i].destroy();
						m_Items[i] = null;
						m_Items.splice(i, 1);
						--cleanNum;
						if (cleanNum == 0)
						{
							return;
						}
					}
				}
			}
		}
		
	}

}